"use client";

import React, { useEffect, useState } from "react";
import styles from "./modal.module.css";
import ordersService from "@/app/services/orders.service";

interface ModalProps {
  onClose: () => void;
  orderId: number;
}

const Modal: React.FC<ModalProps> = ({ onClose, orderId }) => {
  const [loading, setLoading] = useState(true);
  const [items, setItems] = useState([]);

  useEffect(() => {
    ordersService.getOrderItems(orderId).then((response) => {
      setItems(response);
      setLoading(false);
    });
  }, []);

  return (
    <div className={styles.overlay}>
      <div className={styles.modal}>
        <button className={styles.closeButton} onClick={onClose}>
          X
        </button>
        {loading ? (
          <span className="loader"></span>
        ) : (
          <div className={styles.content}>
            <h2>
              Заказ номер: <span className="colored">{orderId}</span>
            </h2>
            <table className="ordersTable">
              <thead>
                <tr>
                  <th>Название</th>
                  <th>Кол-во</th>
                  <th>Стоимость</th>
                </tr>
              </thead>
              <tbody>
                {items &&
                  items.map((item) => (
                    <tr className="row">
                      <td>{item.menuItem.name}</td>
                      <td>{item.quantity}</td>
                      <td>{item.menuItem.price} руб.</td>
                    </tr>
                  ))}
              </tbody>
            </table>
            <h2>
              Общая стоимость:{" "}
              <span className="colored">
                {items.reduce(
                  (accum, item) => accum + item.menuItem.price * item.quantity,
                  0
                )}{" "}
                руб.
              </span>
            </h2>
          </div>
        )}
      </div>
    </div>
  );
};

export default Modal;
